package framework
{
	import mx.rpc.AbstractOperation;
	import mx.rpc.AsyncResponder;
	import mx.rpc.AsyncToken;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;

	public class NetworkChecker
	{
		/**
		 * 网络级别状况：0为断开连接，1为网络堵塞，2为网络一般，3为网络良好
		 */
		[Bindable]
		public static var netStatus:int = 0;
		
		/**
		 * 起始时间
		 */
		private static var startTime:Number;
		
		/**
		 * 初始化函数
		 */
		public static function init():void
		{
			TimerMgr.createTimer(Number(AppGlobal.config.checkNetworkInterval)*1000, checkNetwork);
		}
		
		/**
		 * 检查网络
		 */
		private static function checkNetwork():void
		{
			startTime = new Date().getTime();
			var method:AbstractOperation = AppGlobal.ro.getOperation("testConnection");
			var token:AsyncToken = method.send("test network");
			token.addResponder(new AsyncResponder(resultHandler, faultHandler, token));
		}
		
		/**
		 * 正常返回
		 */
		private static function resultHandler(p_result:ResultEvent, p_token:AsyncToken):void
		{
			var elapseTime:Number = new Date().getTime() - startTime;
			if(elapseTime <= 50){
				netStatus = 3;
			}else if(elapseTime <= 300){
				netStatus = 2;
			}else{
				netStatus = 1;
			}
		}
		
		/**
		 * 连接失败
		 */
		private static function faultHandler(p_fault:FaultEvent, p_token:AsyncToken):void
		{
			netStatus = 0;
		}
	}
}